<?php 
class ExcelOutPut 
{

	/*
	数据导出excel
	title为表头，需传入索引数组，
	data为导出数据，支持26列以内的数据导出
	row 为数据导出的起始行
	name 为文件名
	2017.3.21 by 小黑鼠
	在控制器中调用示例：
	$this->load->library('ExcelOutPut');
	$excel = new ExcelOutPut();
	$title = array('供应商id','供应商名称','账号','地址','联系方式','创建时间');
	$excel->outPutExcel($title,$data['supplier'],2,'供应商列表');
	*/
	
	function outPutExcel($title, $data = '', $row = 2, $name = '数据导出', $title2 = '', $data2 = array()){
		require( 'Phpexcel.php');
		require( 'PHPExcel/Iofactory.php');
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setCreator("管理员")->setLastModifiedBy('杭为科技')->setTitle("数据导出")->setSubject("数据导出");

		// 设置title列数
		$letter = 'A';
		for ($i = 0; $i < count($title) ; $i++) { 
			$chars[] = $letter++;
		}
		// $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

		if(empty($data)){
			return array('code' => 0,'msg' => "无可导出的数据");
		}
		
		//获取数组的键值用于获取传入数据列表每个单元格的具体值	
		$keys = array_keys($data[0]);
		
		//设置excel 的列名
		foreach ($title as $key => $value) {
			$num = 1;
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($chars[$key].$num,$value);
		}
		
		//导出数据到excel
		foreach ($data as $rownum => $rowvalue) {
			$num = $row;
			for($i=0; $i<sizeof($rowvalue); $i++){			
				$objPHPExcel->setActiveSheetIndex(0)->setCellValue($chars[$i].$num,$rowvalue[$keys[$i]]);
			}
			$row += 1;
		}

		// 判断是否存在第二个sheet窗口
		if (!empty($title2)) {
			$msgWorkSheet = new PHPExcel_Worksheet($objPHPExcel, 'Worksheet2'); //创建一个工作表
	        $objPHPExcel->addSheet($msgWorkSheet); //插入工作表
			$objPHPExcel->setActiveSheetIndex(1);
			$objPHPExcel->getActiveSheet()->fromArray($title2, NULL, 'A1');
			$objPHPExcel->getActiveSheet()->fromArray($data2, NULL, 'A2');
		}

		//文件输出
		header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
		return array('code' => 1,'msg' => "数据导出成功");
	}
}